﻿using Abp.Application.Services.Dto;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using Camc.Quality.Authorization.Users;
using Camc.Quality.Bom;
using Camc.Quality.Bop;
using Camc.Quality.DataDictionary;
using Camc.Quality.Dto;
using Camc.Quality.Materials;
using Camc.Quality.ProductionPlan;
using Camc.Quality.Quality;
using Camc.Quality.StoreManagement.StoragePut;
using Camc.Quality.TrepanningManager.ArrowPresetSearch.ArrowPresetSearchInterface;
using Camc.Quality.TrepanningManager.BomAnalyse;
using Camc.Quality.TrepanningManager.BomAnalyseDto;
using Camc.Quality.TrepanningManager.BomNestingInterface;
using Camc.Quality.TrepanningManager.CollectBom;
using Camc.Quality.TrepanningManager.CollectBomDto;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using static Camc.Quality.StoreManagement.StoragePut.StoreStockContent;

namespace Camc.Quality.TrepanningManager.ArrowPresetSearch
{
    public class ArrowPresetSearchAppService : QualityAppServiceBase
    {
        private readonly IRepository<MaterialsContent, Guid> _materialsContentRepository;
        private readonly IRepository<BomDesign, Guid> _bomDesignRepository;
        private readonly IRepository<BomDesignDetail, Guid> _bomDesignDetailRepository;
        private readonly IRepository<CollectBomManager, Guid> _collectBomManagerRepository;
        private readonly IRepository<StoreStock, Guid> _storeStockpository;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        private readonly IRepository<StoreStockContent, Guid> _storeStockContentRepository;
        private readonly IRepository<BomAnalyseContent, Guid> _bomAnalyseContentRepository;
        private readonly IRepository<MaterialsNode, Guid> _materialsNoderepository;
        private readonly BomAnalyseAppService _bomAnalyseAppService;
        private readonly IBomAnalyseExportToExcel _bomAnalyseExportToExcel;
        private readonly CollectBomAppService _collectBomAppService;
        private readonly IRepository<CollectBomManagerChild, Guid> _collectBomManagerChildRepository;
        private readonly MakeTaskAppService _makeTaskAppService;
        private readonly IArrowPresetSearchExportToExcel _IArrowPresetSearchExportToExcel;
        public ArrowPresetSearchAppService(IRepository<MaterialsContent, Guid> materialsContentRepository, IRepository<BomDesign, Guid> bomDesignrepository,
            IRepository<BomDesignDetail, Guid> bomDesignDetailrepository, IRepository<User, long> userRepository,
            IRepository<CollectBomManager, Guid> collectBomManagerrepository, IRepository<StoreStockContent, Guid> storeStockContentRepository,
            IRepository<BomAnalyseContent, Guid> bomAnalyseContentRepository, IRepository<MaterialsNode, Guid> materialsNoderepository,
            BomAnalyseAppService bomAnalyseAppService, BomAnalyseExportToExcel bomAnalyseExportToExcel, IRepository<Sys_Code, Guid> sysCodeRepository, IRepository<StoreStock, Guid> storeStockpository, IRepository<CollectBomManagerChild, Guid> collectBomManagerChildRepository, CollectBomAppService collectBomAppService, MakeTaskAppService makeTaskAppService, IArrowPresetSearchExportToExcel IArrowPresetSearchExportToExcel)
        {
            this._materialsContentRepository = materialsContentRepository;
            this._bomDesignRepository = bomDesignrepository;
            this._bomDesignDetailRepository = bomDesignDetailrepository;
            this._userRepository = userRepository;
            this._collectBomManagerRepository = collectBomManagerrepository;
            this._storeStockContentRepository = storeStockContentRepository;
            this._bomAnalyseContentRepository = bomAnalyseContentRepository;
            this._materialsNoderepository = materialsNoderepository;
            this._bomAnalyseAppService = bomAnalyseAppService;
            this._bomAnalyseExportToExcel = bomAnalyseExportToExcel;
            this._sysCodeRepository = sysCodeRepository;
            this._storeStockpository = storeStockpository;
            this._collectBomManagerChildRepository = collectBomManagerChildRepository;
            this._collectBomAppService = collectBomAppService;
            this._makeTaskAppService = makeTaskAppService;
            this._IArrowPresetSearchExportToExcel = IArrowPresetSearchExportToExcel;
        }
        /// <summary>
        /// 获取发次
        /// </summary>
        /// <returns></returns>
        public async Task<List<CollectBomManagerOtherDto>> GetSendTime(string module)
        {
            var querySendTimeDatas = from querySendTimeData in _bomDesignRepository.GetAll().Where(t => t.Module == module)
                                     select new CollectBomManagerOtherDto
                                     {
                                         label = querySendTimeData.SendTime,
                                         value = querySendTimeData.Id
                                     };
            if (querySendTimeDatas.Count() > 0)
            {
                return querySendTimeDatas.ToList();
            }
            return new List<CollectBomManagerOtherDto>();
        }
        /// <summary>
        /// 查询配套数据汇总芯级数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<BomAnalyseContentDto>> GetBomAalyseCollect(BomAnalyseManagerEditDto input)
        {
            var queryColBomChild = _collectBomManagerChildRepository.GetAll().ToList();
            //先查询汇总bom 是否有对应数据
            var queryCollectBomManagerData = _collectBomManagerRepository.GetAll().Where(t => t.ModuleId == input.ModuleId && t.SendTimeId == input.SendTimeId);
            //根据型号发次找到对应的仓库id
            if (input.ModuleId == Guid.Empty && input.SendTimeId == Guid.Empty)
            {
                return null;
            }
            MakeJobTask makeJobTask = _makeTaskAppService.GetJobNumber(input.SendTimeId, input.ModuleId);
            if (makeJobTask.StoreId == Guid.Empty)
            {
                throw new UserFriendlyException("该型号发次没有关联仓库");
            }

            List<BomDesignDetail> bomDesignDetails = new List<BomDesignDetail>();
            List<BomAnalyseContentDto> bomAnalyseContent = new List<BomAnalyseContentDto>();
            List<CollectBomManagerChild> bomDesigns = new List<CollectBomManagerChild>();
            foreach (CollectBomManager collectBomManager in queryCollectBomManagerData)
            {
                //找出BomdesignId 根据bomdesignID 找出对应芯级 --->部套 --->部套下的组件
                var queryBomXj = _bomDesignDetailRepository.FirstOrDefaultAsync(t => t.BomDesignId == collectBomManager.BomDesignId && t.Id == collectBomManager.XJId).Result;
                if (queryBomXj == null)
                {
                    continue;
                }
                //找出芯级下所有已发布的部套 
                var queryBomBt = _bomDesignDetailRepository.GetAll().Where(t => t.LevelRelationship.StartsWith(queryBomXj.LevelRelationship) && t.BomDesignId == collectBomManager.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件 && t.Status == DocumentStatus.已发布);
                //找出所有零件后 找出每个零件 的bom用量
                if (queryBomBt != null && queryBomBt.Count() > 0)
                {
                    var btLevel = string.Join(",", queryBomBt.Select(t => t.LevelRelationship));
                    //// **根据芯级找出所有部套下的所有组件和零件
                    List<CollectBomManagerChild> queryLj = queryColBomChild.Where(t => t.LevelRelationship.Contains(btLevel) && t.BomDesignId == collectBomManager.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件).ToList();
                    // **根据芯级找出所有部套下的所有组件和零件
                    foreach (BomDesignDetail designDetail in queryBomBt)
                    {
                        //找出每个部套下的零件
                        var materilsList = from queryMaterilsList in queryColBomChild.Where(t => t.LevelRelationship.StartsWith(designDetail.LevelRelationship) && t.BomDesignId == collectBomManager.BomDesignId && (t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件))
                                           join materialsContent in _materialsContentRepository.GetAll() on queryMaterilsList.MaterialId equals materialsContent.Id
                                           join queryMaterilsNode in _materialsNoderepository.GetAll().WhereIf(!input.MaterialTypeName.IsNullOrWhiteSpace(), t => t.MaterialTypeName.Contains(input.MaterialTypeName)) on materialsContent.MaterialsNodeId equals queryMaterilsNode.Id

                                           select queryMaterilsList;
                        bomDesigns.AddRange(materilsList);
                    }

                    //汇总芯级的预配套数量  根据汇总表id 查出预配套表数量
                    // var queryMaterils = _bomAnalyseContentRepository.GetAll().Where(t=>t.CollectBomManagerId == collectBomManager.Id);
                    var queryMaterils = await GetBomAalyseData(collectBomManager, input, bomDesigns, makeJobTask.StoreId);
                    bomAnalyseContent.AddRange(queryMaterils);
                }
            }

            //根据物料id 进行bom用量汇总
            var querybomDesignDetails = bomDesigns.GroupBy(m => new { m.MaterialId }).Select(m => new
            {
                MaterialId = m.Key.MaterialId,
                BomDosageTotalAll = m.Sum(c => c.BomDosageTotalAmount)
            }).ToList();

            var queryMaterAll = from materialsContent in _materialsContentRepository.GetAll()
                                join sumContent in querybomDesignDetails on materialsContent.Id equals sumContent.MaterialId
                                select materialsContent;
            //根据物料id 
            //根据物料id 进行bom用量汇总 只进行预配套数量汇总?
            var querybomAnalyse =
                                  from analyse in (bomAnalyseContent.GroupBy(m => new { m.MaterialsContentId, m.UsableQuantityStock }).Select(t => new BomAnalyseContentDto
                                  {
                                      MaterialsContentId = t.Key.MaterialsContentId,
                                      PreSuiteStockAll = t.Sum(c => c.PreSuiteStock),
                                      StarvingStockAll = t.Sum(c => c.StarvingStock),
                                      DeliveryStockAll = t.Sum(c => c.DeliveryStock),
                                      UsableQuantityStock = t.Key.UsableQuantityStock
                                  }))
                                  select analyse;
            var queryAllBomContent = from materialsContent in queryMaterAll
                                     join materialsNode in _materialsNoderepository.GetAll()
                                     on materialsContent.MaterialsNodeId equals materialsNode.Id
                                     join materialsNodeChild in _materialsNoderepository.GetAll()
                                     on materialsContent.MaterialCategoryId equals materialsNodeChild.Id
                                     join bomAll in querybomDesignDetails on materialsContent.Id equals bomAll.MaterialId
                                     into mn
                                     from ms in mn.DefaultIfEmpty()
                                     join bomAnalyseAll in querybomAnalyse on ms.MaterialId equals bomAnalyseAll.MaterialsContentId
                                              into bm
                                     from bl in bm.DefaultIfEmpty()
                                     join code in _sysCodeRepository.GetAll() on materialsContent.UnitId equals code.Id
                                     into codeData
                                     from cd in codeData.DefaultIfEmpty()
                                     select new BomAnalyseContentDto
                                     {
                                         MaterialsContentId = materialsContent.Id,
                                         MaterialNo = materialsContent.MaterialNo,
                                         MaterialName = materialsContent.MaterialName,
                                         Module = materialsContent.Model,
                                         MaterialTypeName = materialsNode.MaterialTypeName,
                                         MaterialCategoryName = materialsNodeChild.MaterialTypeName,
                                         UnitName = cd == null ? "" : cd.Description,
                                         BomDosageTotalAmount = ms.BomDosageTotalAll,
                                         PreSuiteStock = bl == null ? 0 : bl.PreSuiteStockAll,
                                         StarvingStockAll = (ms.BomDosageTotalAll - (bl == null ? 0 : bl.PreSuiteStockAll)) > (bl == null ? 0 : bl.UsableQuantityStock) ? ms.BomDosageTotalAll - (bl == null ? 0 : bl.UsableQuantityStock + (bl == null ? 0 : bl.PreSuiteStockAll)) : 0,
                                         DeliveryStockAll = bl == null ? 0 : bl.DeliveryStockAll,
                                         UsableQuantityStock = bl == null ? 0 : bl.UsableQuantityStock,
                                         //PreSuiteStatusName = Enum.Parse(typeof(CompleteStatus), bl.PreSuiteStatus.ToString()).ToString(),
                                         PreSuiteStatusName = ms.BomDosageTotalAll == 0 ? "未同步" : ms.BomDosageTotalAll - (bl == null ? 0 : bl.PreSuiteStockAll) > (bl == null ? 0 : bl.UsableQuantityStock) ? CompleteStatus.缺料.ToString() : bl.PreSuiteStockAll == 0 ? CompleteStatus.未预配套.ToString() : ms.BomDosageTotalAll - (bl == null ? 0 : bl.PreSuiteStockAll) <= (bl == null ? 0 : bl.UsableQuantityStock) && ms.BomDosageTotalAll - (bl == null ? 0 : bl.PreSuiteStockAll) <= bl.UsableQuantityStock && (bl == null ? 0 : bl.UsableQuantityStock) != 0 && ms.BomDosageTotalAll > (bl == null ? 0 : bl.PreSuiteStockAll) ? CompleteStatus.预配套中.ToString() : ms.BomDosageTotalAll == (bl == null ? 0 : bl.PreSuiteStockAll) ? CompleteStatus.已预配套.ToString() : "",
                                         PreSuiteName = bl == null ? "" : bl.PreSuiteName,
                                         PreSuiteTime = bl == null ? "" : bl.PreSuiteTime
                                     };
            //var  queryUnion  =from  materilasAll in querybomDesignDetails 
            //                  join materilasParty in queryAllBomContent on materilasAll.MaterialId equals materilasParty.MaterialsContentId
            //                  into materlas from mal in materlas.DefaultIfEmpty()
            //                  select new BomAnalyseContentDto 
            //                  {

            //                  }
            queryAllBomContent = queryAllBomContent.WhereIf(!string.IsNullOrEmpty(input.PreSuiteStatus), t => t.PreSuiteStatusName == input.PreSuiteStatus);
            if (queryAllBomContent != null)
            {
                try
                {
                    var collectBomContents = await queryAllBomContent.OrderBy(s=>s.MaterialNo).OrderBy(s=>s.Module).PageBy(input).ToListAsync();
                    return new PagedResultDto<BomAnalyseContentDto>(queryAllBomContent.Count(), collectBomContents);
                }
                catch (Exception ex)
                {
                    throw new UserFriendlyException("系统内部错误,请重试或联系管理员");
                }
            }
            else
            {
                throw new UserFriendlyException("异常,请重试或联系管理员");
            }
        }
        /// <summary>
        /// 查询配套数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<List<BomAnalyseContentDto>> GetBomAalyseData(CollectBomManager collectBomManager, BomAnalyseManagerEditDto bomAnalyseManagerEditDto, List<CollectBomManagerChild> bomDesigns, Guid storeId)
        {
            //先查询汇总bom 是否有对应数据
            var queryMaterisls = _materialsContentRepository.GetAll().ToList();
            var qeryStoreStock = _storeStockpository.GetAll().ToList();
            var queryXjData = _bomDesignDetailRepository.FirstOrDefaultAsync(t => t.Id == collectBomManager.XJId).Result;
            //根据型号发次找到对应的仓库
            //根据型号发次id 获取预配套信息
            //计算该零件工预配套数量 计算自由库存数量
            var materalisCount = from queryMaterislsContent in queryMaterisls
                                 join queryStoreStocks in qeryStoreStock on queryMaterislsContent.Id equals queryStoreStocks.MaterialsContentId
                                 join queryStoreStockContents in _storeStockContentRepository.GetAll().Where(t => t.BomAnalysecontentId == collectBomManager.Id && t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                 select queryStoreStockContents;

            //计算可用库存数量
            var storeStocksContent = from queryMaterislsContent in queryMaterisls
                                     join queryStoreStocks in qeryStoreStock on queryMaterislsContent.Id equals queryStoreStocks.MaterialsContentId
                                     join queryStoreStockContents in _storeStockContentRepository.GetAll().
                                     Where(t => t.SendTimeId.Contains(collectBomManager.SendTimeId.ToString()) && t.Batch == "01" && t.IsPreSuit == IsSuits.否 && t.ProductCodeId.Contains(collectBomManager.ModuleId.ToString()) && t.BomAnalysecontentId == null) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                     select queryStoreStockContents;
            List<CollectBomMaterialsContentDto> collectBomMaterialsContentDtos = _collectBomAppService.GetCollectBomMaterialsContent(collectBomManager.XJId);
           // var cc = collectBomMaterialsContentDtos.ToList();
            //关联物料建模 和 仓库库存信息
            var queryBomAnalyseContents = from queryMaterislsContent in queryMaterisls
                                          join queryMaterilsType in _materialsNoderepository.GetAll()
                                          .WhereIf(!bomAnalyseManagerEditDto.MaterialTypeName.IsNullOrWhiteSpace(), t => t.MaterialTypeName.StartsWith(bomAnalyseManagerEditDto.MaterialTypeName))
                                          on queryMaterislsContent.MaterialsNodeId equals queryMaterilsType.Id
                                          join queryStoreStocks in qeryStoreStock on
                                            queryMaterislsContent.Id equals queryStoreStocks.MaterialsContentId
                                          join bomCollect in collectBomMaterialsContentDtos on queryStoreStocks.MaterialsContentId equals bomCollect.MerialsId
                                          join code in _sysCodeRepository.GetAll() on queryMaterislsContent.UnitId equals code.Id
                                          into codeData
                                          from cd in codeData.DefaultIfEmpty()
                                          where queryStoreStocks.StoreId == storeId
                                          select new BomAnalyseContentDto
                                          {
                                              // Id = bly.Id,
                                              XJId = collectBomManager.XJId,
                                              // XJCode =
                                              MaterialNo = queryMaterislsContent.MaterialNo,
                                              MaterialName = queryMaterislsContent.MaterialName,
                                              MaterialsContentId = queryMaterislsContent.Id,
                                              Module = queryMaterislsContent.Model,
                                              UnitName = cd.Description,
                                              BomDosageTotalAmount = bomCollect.Unit1BomDosageXj,
                                              UsableQuantityStock = storeStocksContent.Count(t => t.StoreStockId == queryStoreStocks.Id),
                                              // 自由库存数量 ==总数量-可用库存数量?
                                              FreeQuantityStock = queryStoreStocks.FreeQuantityStock,
                                              //预配套数量
                                              PreSuiteStock = materalisCount.Count(t => t.StoreStockId == queryStoreStocks.Id),
                                              //缺料数量 芯级用量 - 预配套数量
                                              StarvingStock = (bomCollect.Unit1BomDosageXj - materalisCount.Count(t => t.StoreStockId == queryStoreStocks.Id)) > storeStocksContent.Count(t => t.StoreStockId == queryStoreStocks.Id) ? bomCollect.Unit1BomDosageXj - (storeStocksContent.Count(t => t.StoreStockId == queryStoreStocks.Id) + materalisCount.Count(t => t.StoreStockId == queryStoreStocks.Id)) : 0,
                                              //出库数量
                                              DeliveryStock = queryStoreStocks.DeliveryStock,
                                              ////预配套状态
                                              //PreSuiteStatus = bly.PreSuiteStatus,
                                              //预配套人
                                              PreSuiteName = queryStoreStocks.PreSuiteName,
                                              ////预配套时间
                                              //PreSuiteTime = bly.PreSuiteTime,
                                              //入库主表ID
                                              //   StoreStockId = queryStoreStockContent.Id,
                                              //发次
                                              SendTimeId = bomAnalyseManagerEditDto.SendTimeId,
                                              //产品图号
                                              ProductCode = queryMaterislsContent.MaterialNo,
                                              PreSuiteStatus = queryStoreStocks.PreSuiteStatus,
                                              CreationTime = queryStoreStocks.CreationTime
                                          };
            return queryBomAnalyseContents.ToList();
        }
        /// <summary>
        /// 导出主页预配套内容
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<string> GetMaterialsContentToExcel(BomAnalyseManagerEditDto input)
        {
            //先查询汇总bom 是否有对应数据
            var queryCollectBomManagerData = _collectBomManagerRepository.GetAll().Where(t => t.ModuleId == input.ModuleId && t.SendTimeId == input.SendTimeId);
            //根据型号发次找到对应的仓库id
            if (input.ModuleId == Guid.Empty && input.SendTimeId == Guid.Empty)
            {
                return null;
            }
            MakeJobTask makeJobTask = _makeTaskAppService.GetJobNumber(input.SendTimeId, input.ModuleId);
            if (makeJobTask.StoreId == Guid.Empty)
            {
                throw new UserFriendlyException("该型号发次没有关联仓库");
            }

            List<BomDesignDetail> bomDesignDetails = new List<BomDesignDetail>();
            List<BomAnalyseContentDto> bomAnalyseContent = new List<BomAnalyseContentDto>();
            List<CollectBomManagerChild> bomDesigns = new List<CollectBomManagerChild>();
            foreach (CollectBomManager collectBomManager in queryCollectBomManagerData)
            {
                //找出BomdesignId 根据bomdesignID 找出对应芯级 --->部套 --->部套下的组件
                var queryBomXj = _bomDesignDetailRepository.FirstOrDefaultAsync(t => t.BomDesignId == collectBomManager.BomDesignId && t.Id == collectBomManager.XJId).Result;
                if (queryBomXj == null)
                {
                    continue;
                }
                //找出芯级下所有已发布的部套 
                var queryBomBt = _bomDesignDetailRepository.GetAll().Where(t => t.LevelRelationship.StartsWith(queryBomXj.LevelRelationship) && t.BomDesignId == collectBomManager.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件 && t.Status == DocumentStatus.已发布);
                //找出所有零件后 找出每个零件 的bom用量

                if (queryBomBt != null && queryBomBt.Count() > 0)
                {
                    var btLevel = string.Join(",", queryBomBt.Select(t => t.LevelRelationship));
                    //// **根据芯级找出所有部套下的所有组件和零件
                    List<CollectBomManagerChild> queryLj = _collectBomManagerChildRepository.GetAll().Where(t => t.LevelRelationship.Contains(btLevel) && t.BomDesignId == collectBomManager.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件).ToList();
                    // **根据芯级找出所有部套下的所有组件和零件
                    foreach (BomDesignDetail designDetail in queryBomBt)
                    {
                        //找出每个部套下的零件
                        var materilsList = from queryMaterilsList in _collectBomManagerChildRepository.GetAll().Where(t => t.LevelRelationship.StartsWith(designDetail.LevelRelationship) && t.BomDesignId == collectBomManager.BomDesignId && (t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件))
                                           join materialsContent in _materialsContentRepository.GetAll() on queryMaterilsList.MaterialId equals materialsContent.Id
                                           join queryMaterilsNode in _materialsNoderepository.GetAll().WhereIf(!input.MaterialTypeName.IsNullOrWhiteSpace(), t => t.MaterialTypeName == input.MaterialTypeName) on materialsContent.MaterialsNodeId equals queryMaterilsNode.Id

                                           select queryMaterilsList;
                        bomDesigns.AddRange(materilsList);
                    }

                    //汇总芯级的预配套数量  根据汇总表id 查出预配套表数量
                    // var queryMaterils = _bomAnalyseContentRepository.GetAll().Where(t=>t.CollectBomManagerId == collectBomManager.Id);
                    var queryMaterils = await GetBomAalyseData(collectBomManager, input, bomDesigns, makeJobTask.StoreId);
                    bomAnalyseContent.AddRange(queryMaterils);
                }
            }

            //根据物料id 进行bom用量汇总
            var querybomDesignDetails = bomDesigns.GroupBy(m => new { m.MaterialId }).Select(m => new
            {
                MaterialId = m.Key.MaterialId,
                BomDosageTotalAll = m.Sum(c => c.BomDosageTotalAmount)
            }).ToList();

            var queryMaterAll = from materialsContent in _materialsContentRepository.GetAll()
                                join sumContent in querybomDesignDetails on materialsContent.Id equals sumContent.MaterialId
                                select materialsContent;
            //根据物料id 
            //根据物料id 进行bom用量汇总 只进行预配套数量汇总?
            var querybomAnalyse =
                                  from analyse in (bomAnalyseContent.GroupBy(m => new { m.MaterialsContentId, m.UsableQuantityStock }).Select(t => new BomAnalyseContentDto
                                  {
                                      MaterialsContentId = t.Key.MaterialsContentId,
                                      PreSuiteStockAll = t.Sum(c => c.PreSuiteStock),
                                      StarvingStockAll = t.Sum(c => c.StarvingStock),
                                      DeliveryStockAll = t.Sum(c => c.DeliveryStock),
                                      UsableQuantityStock = t.Key.UsableQuantityStock
                                  }))
                                  select analyse;

            var queryAllBomContent = from materialsContent in queryMaterAll
                                     join materialsNode in _materialsNoderepository.GetAll()
                                     on materialsContent.MaterialsNodeId equals materialsNode.Id
                                     join materialsNodeChild in _materialsNoderepository.GetAll()
                                     on materialsContent.MaterialCategoryId equals materialsNodeChild.Id
                                     join bomAll in querybomDesignDetails on materialsContent.Id equals bomAll.MaterialId
                                     into mn
                                     from ms in mn.DefaultIfEmpty()
                                     join bomAnalyseAll in querybomAnalyse on ms.MaterialId equals bomAnalyseAll.MaterialsContentId
                                              into bm
                                     from bl in bm.DefaultIfEmpty()
                                     join code in _sysCodeRepository.GetAll() on materialsContent.UnitId equals code.Id
                                     into codeData
                                     from cd in codeData.DefaultIfEmpty()
                                     select new BomAnalyseContentDto
                                     {
                                         MaterialsContentId = materialsContent.Id,
                                         MaterialNo = materialsContent.MaterialNo,
                                         MaterialName = materialsContent.MaterialName,
                                         Module = materialsContent.Model,
                                         MaterialTypeName = materialsNode.MaterialTypeName,
                                         MaterialCategoryName = materialsNodeChild.MaterialTypeName,
                                         UnitName = cd == null ? "" : cd.Description,
                                         BomDosageTotalAmount = ms.BomDosageTotalAll,
                                         PreSuiteStock = bl == null ? 0 : bl.PreSuiteStockAll,
                                         StarvingStockAll = (ms.BomDosageTotalAll - (bl == null ? 0 : bl.PreSuiteStockAll)) > (bl == null ? 0 : bl.UsableQuantityStock) ? ms.BomDosageTotalAll - (bl == null ? 0 : bl.UsableQuantityStock + (bl == null ? 0 : bl.PreSuiteStockAll)) : 0,
                                         DeliveryStockAll = bl == null ? 0 : bl.DeliveryStockAll,
                                         UsableQuantityStock = bl == null ? 0 : bl.UsableQuantityStock,
                                         //PreSuiteStatusName = Enum.Parse(typeof(CompleteStatus), bl.PreSuiteStatus.ToString()).ToString(),
                                         PreSuiteStatusName = ms.BomDosageTotalAll == 0 ? "未同步" : ms.BomDosageTotalAll - (bl == null ? 0 : bl.PreSuiteStockAll) > (bl == null ? 0 : bl.UsableQuantityStock) ? CompleteStatus.缺料.ToString() : bl.PreSuiteStockAll == 0 ? CompleteStatus.未预配套.ToString() : ms.BomDosageTotalAll - (bl == null ? 0 : bl.PreSuiteStockAll) <= (bl == null ? 0 : bl.UsableQuantityStock) && ms.BomDosageTotalAll - (bl == null ? 0 : bl.PreSuiteStockAll) <= bl.UsableQuantityStock && (bl == null ? 0 : bl.UsableQuantityStock) != 0 && ms.BomDosageTotalAll > (bl == null ? 0 : bl.PreSuiteStockAll) ? CompleteStatus.预配套中.ToString() : ms.BomDosageTotalAll == (bl == null ? 0 : bl.PreSuiteStockAll) ? CompleteStatus.已预配套.ToString() : "",
                                         PreSuiteName = bl == null ? "" : bl.PreSuiteName,
                                         PreSuiteTime = bl == null ? "" : bl.PreSuiteTime
                                     };
            //var  queryUnion  =from  materilasAll in querybomDesignDetails 
            //                  join materilasParty in queryAllBomContent on materilasAll.MaterialId equals materilasParty.MaterialsContentId
            //                  into materlas from mal in materlas.DefaultIfEmpty()
            //                  select new BomAnalyseContentDto 
            //                  {

            //                  }
            queryAllBomContent = queryAllBomContent.WhereIf(!input.PreSuiteStatus.IsNullOrWhiteSpace(), t => t.PreSuiteStatusName == input.PreSuiteStatus);
            if (queryAllBomContent != null) 
            {
                queryAllBomContent = queryAllBomContent.OrderBy(s => s.MaterialNo).OrderBy(s=>s.Module
                );
                return _IArrowPresetSearchExportToExcel.ExportToFile(queryAllBomContent.ToList());
            }
            return null;
        }
    }
}
